package com.device_manager.service.impl;

import com.device_manager.dto.PageShipmentDTO;
import com.device_manager.dto.ShipmentDTO;
import com.device_manager.entity.Box;
import com.device_manager.entity.Device;
import com.device_manager.entity.Shipment;
import com.device_manager.mapper.BoxMapper;
import com.device_manager.mapper.DeviceMapper;
import com.device_manager.mapper.ShipmentMapper;
import com.device_manager.result.PageResult;
import com.device_manager.result.Result;
import com.device_manager.service.ShipmentService;
import com.device_manager.vo.PageShipmentListVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class ShipmentServiceImpl implements ShipmentService {
    @Autowired
    private ShipmentMapper shipmentMapper;
    @Autowired
    private BoxMapper  boxMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Override
    public Result<String> addShipment(ShipmentDTO shipmentDTO){

        /**
         * 1.判断设备号是否已存在
         * 2.插入发货记录
         * 3.插入箱子信息
         * 4.插入设备信息
         */
        try {
            //1.判断设备号是否已存在
            List<String> returnedDevices = new ArrayList<>();
            for (ShipmentDTO.DeviceDTO deviceDTO : shipmentDTO.getDevices()) {
                if (deviceMapper.selectDeviceMac(deviceDTO.getDeviceMac())) {
                    returnedDevices.add(deviceDTO.getDeviceMac());
//                    throw new RuntimeException("设备" + deviceDTO.getDeviceMac()+"已存在:");
                }
            }
            //2.判断箱子号是否已存在
            List<String> returnedBoxes = new ArrayList<>();
            if (shipmentDTO.getBoxes() != null && !shipmentDTO.getBoxes().isEmpty()) {
                for (ShipmentDTO.BoxDTO returnBox : shipmentDTO.getBoxes()) {
                    if (boxMapper.selectBoxNumber(returnBox.getBoxNumber()))
                        returnedBoxes.add(returnBox.getBoxNumber());
                }
            }
            // 3. 如果有验证错误，返回错误结果
            if (!returnedDevices.isEmpty() || !returnedBoxes.isEmpty()) {
                StringBuilder errorMsg = new StringBuilder("入库失败: ");

                if (!returnedDevices.isEmpty()) {
                    errorMsg.append("以下设备已入库: ").append(String.join(", ", returnedDevices));
                    log.error(String.valueOf(errorMsg));
                }

                if (!returnedBoxes.isEmpty()) {
                    if (!returnedDevices.isEmpty()) errorMsg.append("; ");
                    errorMsg.append("以下箱子已入库: ").append(String.join(", ", returnedBoxes));
                    log.error(String.valueOf(errorMsg));
                }
                return Result.error(errorMsg.toString());
            }
            //4.插入发货记录
            Shipment record = new Shipment();
            record.setShipmentOrder(shipmentDTO.getShipmentOrder());
            record.setShipper(shipmentDTO.getShipper());
            record.setReceiver(shipmentDTO.getReceiver());
            record.setDeviceCount(shipmentDTO.getDeviceCount());
            //发货时间为当前时间
            record.setShipmentTime(LocalDateTime.now());
            shipmentMapper.addShipment(record);
            log.info("新增发货记录成功", record.getShipmentId());
            //5.插入箱子信息
            for (ShipmentDTO.BoxDTO boxDTO : shipmentDTO.getBoxes()) {
                Box box = new Box();
                box.setBoxNumber(boxDTO.getBoxNumber());
                box.setBoxFlag(boxDTO.getBoxFlag());
                box.setTotalDeviceCount(boxDTO.getTotalDeviceCount());
                box.setShipmentOrder(record.getShipmentOrder());
                box.setCreateTime(LocalDateTime.now());
                boxMapper.addBox(box);
                log.info("新增箱子信息成功", box.getBoxNumber());
            }
            // 6. 插入设备信息
            for (ShipmentDTO.DeviceDTO deviceDTO : shipmentDTO.getDevices()) {
                Device device = new Device();
                device.setDeviceMac(deviceDTO.getDeviceMac());
                device.setDeviceType(deviceDTO.getDeviceType());
                device.setCreateTime(LocalDateTime.now());
                device.setBoxNumber(deviceDTO.getBoxNumber());
                device.setShipmentOrder(shipmentDTO.getShipmentOrder());
                deviceMapper.createDevice(device);
                log.info("新增设备信息成功");
            }
            return Result.success("处理发货单成功");
        }
        catch (Exception e) {
            throw new RuntimeException("处理发货单失败,事务回滚", e);
        }
    }


    /**
     * 查询发货单列表
     * @param pageShipmentDTO
     * @return
     */
    @Override
    public PageResult<PageShipmentListVO> shipmentList(PageShipmentDTO pageShipmentDTO) {
        PageHelper.startPage(pageShipmentDTO.getPage(),pageShipmentDTO.getPageSize());
        Page<PageShipmentListVO> shipments = shipmentMapper.selectShipmentList(pageShipmentDTO);
        long  total   = shipments.getTotal();
        List records = shipments.getResult();
        return new PageResult<>(total,records);
    }
}


